<template>
  <div>
    <Table
      :loading="loading"
      border
      ref="selection"
      :columns="columns"
      :data="thisShoppingCart"
      size="large"
      no-data-text="您的购物车没有商品，请先添加商品到购物车再点击购买"
      @on-selection-change="handleOnSelectionChange"
    >
      <Row class="expand-row"> </Row>
      <template slot-scope="{ row }" slot="action">
        <Button type="error" @click="remove(row.orderSn)">删除</Button>
      </template>
    </Table>
    <span class="total"> 总价：{{ total }} </span>
    <div class="go-to">
      <Button @click="goTo" type="primary">去付款</Button>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { editShoppingCart, deleteShoppingCart, getShoppingCartByTempCart } from '~/api/cart'
import { addingOrder } from '~/api/order'
export default {
  name: 'MyShoppingCart',
  data() {
    return {
      columns: [
        {
          type: 'selection',
          width: 70,
          align: 'center'
        },
        {
          title: '标题',
          width: 500,
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.goodDetail.name
            return h('div', resultStr)
          }
        },
        {
          title: '图片',
          key: 'img',
          align: 'center',
          width: 86,
          render: (h, params) => {
            return h('div', [
              h('img', {
                attrs: {
                  src: params.row.goodDetail.imgUrls[0],
                  class: 'cartImg'
                },
                style: {
                  width: '50px'
                }
              })
            ])
          }
        },
        {
          title: '单价',
          width: 90,
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.goodDetail.price
            return h('div', resultStr)
          }
        },
        {
          title: '数量',
          key: 'qty',
          width: 250,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  max: 100,
                  min: 1,
                  value: params.row.qty,
                  size: 'large'
                },
                on: {
                  'on-change': (value) => {
                    this.editShoppingCart(params.row.goodId, value)
                  }
                }
              })
            ])
          }
        },
        {
          title: '该商品总价',
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.qty * params.row.goodDetail.price
            return h('div', resultStr)
          }
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  size: 'large',
                  type: 'error'

                },
                on: {
                  'click': () => {
                    this.deleteShoppingCart(params.row.goodId)
                  }
                }
              }, '移除')
            ])
          }
        }
      ],
      // 购物车数据
      thisShoppingCart: [{
        goodId: 0,
        qty: 1,
        goodDetail: {
          price: 0,
          imgUrls: [''],
          name: ''
        }
      }],
      // 是否是临时购物车
      tempFlag: false,
      total: 0,
      selection: [],
      loading: true
    }
  },
  created() {
    // 初始化购物车页面
    this.reset()
  },
  methods: {
    ...mapActions('cart', ['getShoppingCart', 'editStoreShoppingCart', 'deleteStoreShoppingCart']),
    handleOnSelectionChange(status) {
      this.selection = status
      let total = 0
      for (let i = 0; i < status.length; i++) {
        total += status[i].goodDetail.price * status[i].qty
      }
      this.total = total
    },
    reset() {
      this.getShoppingCart().then(res => {
        if (!res) {
          // 未登录
          if (this.$store.state.cart.tempShoppingCart.length > 0) {
            this.tempFlag = true
            // 临时购物车的id列表
            const idList = []
            for (let i = 0; i < this.$store.state.cart.tempShoppingCart.length; i++) {
              idList.push(this.$store.state.cart.tempShoppingCart[i].gid)
            }
            // 将数据进行包装，变为与登录用户一样的数据
            getShoppingCartByTempCart(idList).then(res => {
              res.data.forEach(value => {
                value.qty = this.$store.state.cart.tempShoppingCart.filter(
                  goods => {
                    return parseInt(goods.gid) === value.id
                  }
                )[0].count
                value.goodDetail = {
                  name: value.name,
                  price: value.price,
                  imgUrls: value.imgUrls
                }
                value.goodId = value.id
              })
              this.thisShoppingCart = res.data
              this.loading = false
            })
          } else {
            this.thisShoppingCart = []
            this.loading = false
          }
        } else {
          // 登陆
          this.tempFlag = false
          this.thisShoppingCart = JSON.parse(JSON.stringify(res.data))
          this.loading = false
        }
      })
    },
    goTo() {
      if (this.selection.length > 0) {
        const uid = this.$store.state.user.userInfo.uid
        const goodsId = []
        this.selection.forEach((e) => {
          const value = {}
          value.goodId = e.goodId
          value.qty = e.qty
          goodsId.push(value)
        })
        addingOrder(uid, goodsId).then(res => {
          if (res.code === 200) this.$router.push('/order')
        })
      } else {
        this.$Message.error('请先选择商品')
      }
    },
    // 改变购物车商品数量
    editShoppingCart(goods_id, value) {
      let index = -1
      this.thisShoppingCart.forEach((currentValue, i, arr) => {
        if (currentValue.goodId === goods_id) {
          index = i
        }
      })
      // 未登录下
      if (this.tempFlag) {
        this.editStoreShoppingCart({ goods_id, value })
        this.thisShoppingCart[index].qty = value
        // 传入商品id与数量
      } else {
        const uid = this.$store.state.user.userInfo.uid
        // 已登录情况，发出请求即可
        editShoppingCart(goods_id, value, uid).then(res => {
          if (res.code === 200) {
            this.thisShoppingCart[index].qty = value
          }
        })
      }
    },
    // 删除该商品
    deleteShoppingCart(goods_id) {
      let index = -1
      this.thisShoppingCart.forEach((currentValue, i) => {
        if (currentValue.goodId === goods_id) {
          index = i
        }
      })
      // 未登录下
      if (this.tempFlag) {
        this.deleteStoreShoppingCart(goods_id)
        this.thisShoppingCart.splice(index, 1)
      } else {
        // 已登录情况，发出请求即可
        const uid = this.$store.state.user.userInfo.uid
        deleteShoppingCart([goods_id], uid).then(res => {
          if (res.code === 200) {
            this.thisShoppingCart.splice(index, 1)
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.total,
.go-to {
  margin: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
